import React, { useState } from 'react';
import { Modal, Form, Table, message } from 'antd';
import { Pagination } from '@/components';
import request from '@/utils/request';
import styles from './index.less';
import RadioSelectFormItem from '../RadioSelect';
import { getTaskUserConfig, saveTaskUserConfig, getEmployeeList } from '../../services';

// 用于modal框的几种状态
const ModalTypes = {
    APPLY: 'apply', // 发起估算
    NONEED: 'noNeed', // 移入无需估算
    GOBACK: 'goback' //
};

const ApplyAssessmentModal = ({
    form,
    visible,
    setVisible,
    onOk,
    onCancel,
    modalTypes,
    curList = [],
    curAllList = [],
    clickType
}) => {
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [dataSource, setDataSource] = React.useState([]);
    const [userConfig, setUserConfig] = React.useState(null);
    const [employeeList, setEmployeeList] = useState([]);
    const [pagination, setPagination] = React.useState({
        pageNo: 1,
        pageSize: 10
    });

    const updateOptions = async (companyId = user.companyId) => {
        const ret = [];
        const res = await getEmployeeList(companyId);
        if (res.code === 10000) {
            res.data.forEach(item => {
                // 过滤掉admin
                // if (!(item.id === 1 || item.employeeName === 'admin')) {
                ret.push({
                    label: item.employeeName,
                    value: JSON.stringify({ employeeCode: item.employeeCode, employeeName: item.employeeName })
                });
                // }
            });
        }
        setEmployeeList(ret);
        // setPersonOptions(ret);
    };

    React.useEffect(() => {
        updateOptions(user.companyId);
    }, [user.companyId]);

    const getTitle = () => {
        if (modalTypes === 'apply' && clickType === 'single') {
            return '发起估算';
        }
        if (modalTypes === 'apply' && clickType === 'all') {
            return '批量发起估算';
        }
        if (modalTypes === 'noNeed' && clickType === 'single') {
            return '移入无需估算';
        }
        if (modalTypes === 'noNeed' && clickType === 'all') {
            return '批量移入无需估算';
        }
        if (modalTypes === 'goback' && clickType === 'single') {
            return '移回待发起';
        }
        if (modalTypes === 'goback' && clickType === 'all') {
            return '批量移回待发起';
        }
        return '';
    };
    const columns = [
        {
            title: '序号',
            render: (text, record, index) => index + 1
        },
        {
            title: '任务编号',
            dataIndex: 'taskNo'
        },
        {
            title: '名称',
            dataIndex: 'taskName',
            render: text => (
                <div
                    style={{
                        width: '100%',
                        minWidth: 200,
                        position: 'relative'
                    }}
                >
                    <span
                        style={{
                            position: 'absolute',
                            left: 0,
                            right: 0,
                            top: 0,
                            transform: 'translateY(-50%)',
                            overflow: 'hidden',
                            whiteSpace: 'nowrap',
                            textOverflow: 'ellipsis'
                        }}
                        title={text}
                    >
                        {text}
                    </span>
                </div>
            )
        },
        {
            title: '执行人',
            dataIndex: 'taskExecutor',
            width: 100
        },
        {
            title: '所属部门',
            dataIndex: 'executorDepartmentName'
        }
    ];

    const featchApply = async (values, taskIds) => {
        const result = await request('/api/oa/v1/work/task/estimation/starttaskestimation', {
            method: 'POST',
            data: {
                taskIds, // 任务集合
                taskRoleType: values.taskRoleType, // 估算人类型 1角色2自定义
                roleTypes: values.taskRoleType === '1' ? values.roleTypes : [], // 角色类型集合
                employeeCodeList: values.taskRoleType === '2' ? values.employees.map(item => JSON.parse(item)) : [] // 自定义集合
            }
        });
        if (result.code === 10000) {
            message.success('发起估算成功');
            setVisible(false);
            onOk();
            form.resetFields();
            setConfirmLoading(false);
        } else {
            message.error(result.msg);
            setConfirmLoading(false);
        }
    };
    const featchNoNeed = async taskIds => {
        const result = await request('/api/oa/v1/work/task/estimation/movebacktononeedestimation', {
            method: 'POST',
            data: {
                taskIds
            }
        });
        if (result.code === 10000) {
            message.success('操作成功');
            onOk();
            setVisible(false);
            form.resetFields();
            setConfirmLoading(false);
        } else {
            message.error(result.msg);
            setConfirmLoading(false);
        }
    };
    const featchGoback = async taskIds => {
        const result = await request('/api/oa/v1/work/task/estimation/movebacktowaitingestimation', {
            method: 'POST',
            data: {
                taskIds
            }
        });
        if (result.code === 10000) {
            message.success('操作成功');
            onOk();
            setVisible(false);
            form.resetFields();
            setConfirmLoading(false);
        } else {
            message.error(result.msg);
            setConfirmLoading(false);
        }
    };

    const getTaskUsers = async () => {
        const res = await getTaskUserConfig('estimation_custom_employee_list');
        const { code, data } = res;
        if (code === 10000) {
            // console.log(data);
            setUserConfig(data);
        }
    };

    const saveTaskUsers = async values => {
        if (values.taskRoleType !== '2') {
            return;
        }
        const res = await saveTaskUserConfig({
            ...userConfig,
            configType: 'estimation_custom_employee_list',
            configJson: JSON.stringify(values.employees.map(item => JSON.parse(item)))
        });
        const { code } = res;
        if (code === 10000) {
            getTaskUsers();
        }
    };

    const handleOk = () => {
        form.validateFields(async (err, values) => {
            // console.log('handleOk -> values', values);
            if (!err) {
                setConfirmLoading(true);
                const taskIds = dataSource.map(item => item.id);

                if (modalTypes === 'apply') {
                    featchApply(values, taskIds);
                    saveTaskUsers(values);
                }
                if (modalTypes === 'noNeed') {
                    featchNoNeed(taskIds);
                }
                if (modalTypes === 'goback') {
                    featchGoback(taskIds);
                }
            }
            return '';
        });
    };
    const handleCancel = () => {
        if (onCancel) onCancel();
        setVisible(false);
    };
    const formLayout = {
        wrapperCol: { span: 16 },
        labelCol: { span: 6 }
    };
    const renderText = () => {
        if (modalTypes === ModalTypes.NONEED) {
            return <div className={styles.text}>确定对以下任务移入无需估算？</div>;
        }
        if (modalTypes === ModalTypes.GOBACK) {
            return <div className={styles.text}>确定将以下任务移回待发起？</div>;
        }
        return '';
    };
    React.useEffect(() => {
        if (visible) {
            setDataSource(
                clickType === 'all' ? curAllList.sort((a, b) => a.id - b.id) : curList.sort((a, b) => a.id - b.id)
            );
        }
    }, [curList, curAllList, dataSource, clickType, visible]);

    React.useEffect(() => {
        getTaskUsers();
    }, []);

    // 分页操作
    const handlePaginationChange = _pagination => {
        const { current, ...rest } = _pagination;
        setPagination({
            ...pagination,
            ...rest,
            pageNo: current
        });
    };
    return (
        <Modal
            title={getTitle()}
            width={864}
            visible={visible}
            confirmLoading={confirmLoading}
            onOk={handleOk}
            destroyOnClose
            onCancel={handleCancel}
            // footer={null}
        >
            {ModalTypes.APPLY === modalTypes ? (
                <React.Fragment>
                    <Form {...formLayout}>
                        <RadioSelectFormItem
                            form={form}
                            label="请选择估算人"
                            fieldMessage="请选择估算人类型"
                            customMessage="请选择自定义估算人"
                            userConfig={userConfig}
                            defaultType="2"
                            employeeList={employeeList}
                            roleOptions={[
                                { label: '发起人', value: '1' },
                                { label: '审核人', value: '2' },
                                { label: '参与人', value: '4' },
                                { label: '验收人', value: '5' }
                            ]}
                        />
                    </Form>
                    <div>已选任务清单</div>
                </React.Fragment>
            ) : null}
            {renderText()}
            <Table
                rowKey="id"
                bordered={false}
                columns={columns}
                dataSource={dataSource.slice(
                    (pagination.pageNo - 1) * pagination.pageSize,
                    pagination.pageNo * pagination.pageSize
                )}
                pagination={false}
            />

            <Pagination
                total={dataSource.length}
                current={Number(pagination.pageNo)}
                pageSize={Number(pagination.pageSize)}
                onChange={handlePaginationChange}
            />
        </Modal>
    );
};
export default Form.create()(ApplyAssessmentModal);
